<template>
  <div class="insurer-info-container">
    <h2 class="title">投保人信息</h2>
    <!-- 车辆类型选择 -->
    <div class="container">车辆类型</div>
    <van-radio-group v-model="formfullData.isUnitVehicle" style="display: flex;">
      <van-radio name="0">个人车辆</van-radio>
      <van-radio name="1" class="company">单位车辆</van-radio>
    </van-radio-group>
    <!-- 拍摄提示 -->
    <p class="tip">
      <van-icon name="warning-o" color="#f56c6c" />
      请去掉证件保护套，注意避免反光，确保拍摄清晰
    </p>
    <!-- 身份证拍照/上传区域 -->
    <div class="id-card-box">
      <div class="id-card-item" @click="handleTakePhoto('back')">
        <van-icon name="photograph" v-if="!singleImageUrlReverse" size="32" color="#999" />
        <p v-if="!singleImageUrlReverse">身份证人像面</p>
        <p v-if="!singleImageUrlReverse">点击拍摄或上传</p>
        <van-uploader
          v-model="singleFileListReverseList"
          :max-count="1"
          :after-read="handleSingleReadreverseCard"
          :before-delete="handleSingleDeletereverseCard"
          @delete="handleSingleDeletereverseCard"
        >
          <van-button icon="photograph" type="primary">上传照片</van-button>
        </van-uploader>
      </div>
      <div class="id-card-item" @click="handleTakePhoto('front')">
        <van-icon name="photograph" v-if="!singleImageUrl" size="32" color="#999" />
        <p v-if="!singleImageUrl">身份证国徽面</p>
        <p v-if="!singleImageUrl">点击拍摄或上传</p>
        <van-uploader
          v-model="singleFileList"
          :max-count="1"
          :after-read="handleSingleReadfrontCard"
          :before-delete="handleSingleDeletefrontCard"
          @delete="handleSingleDeletefrontCard"
        >
          <van-button icon="photograph" type="primary">上传照片</van-button>
        </van-uploader>
      </div>
    </div>
    <!-- 姓名输入 -->
    <van-field
      v-model="formfullData.fullName"
      :label="formfullData.isUnitVehicle == 0?'姓名':'法人姓名'"
      placeholder="请输入姓名,或通过身份证OCR识别"
    >
    </van-field>
    <!-- 身份证号输入 -->
    <van-field
      v-model="formfullData.idCard"
      label="身份证号码"
      placeholder="请输入身份证号码,或通过OCR识别"
    >
    </van-field>
    <!-- 地区选择 -->
    <van-field
      v-model="isHebeiProvinceName"
      label="是否河北省"
      placeholder="请选择"
      readonly
      @click="showRegionPicker = true"
    />
    <van-field
      v-model="formfullData.issuingAuthority"
      label="签发机关"
      placeholder="请输入签发机关"
    >
    </van-field>
    <!-- 有效期限输入 -->
    <van-field
      v-model="formfullData.validPeriod"
      label="有效期限"
      placeholder="请输入有效期限"
    >
    </van-field>
    <!-- 地区选择器（弹出层） -->
    <van-popup v-model:show="showRegionPicker" position="bottom">
      <van-picker
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChange"
      />
    </van-popup>
    <div class="id-card-item" >
        <van-icon name="photograph" v-if="!usccImageUrlValue" size="32" color="#999" />
        <p v-if="!usccImageUrlValue">上传统一社会信用代码证照片</p>
        <van-uploader
          v-model="usccImageUrlList"
          :max-count="1"
          :after-read="uploadUsccImageUrl"
          :before-delete="delUsccImageUrl"
          @delete="delUsccImageUrl"
        >
          <van-button icon="photograph" type="primary">上传照片</van-button>
        </van-uploader>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import { showToast } from 'vant';
import {
	recognizeOcr, ytbUpload
} from '/@/api/auth/ytb.ts'
import { userInfoStrore } from '/@/stores/userInfoStore'

const store = userInfoStrore()
const formfullData = ref({isUnitVehicle: 0})
const formfullDataSeeion = JSON.parse(sessionStorage.getItem('formfullData'))
const isHebeiProvinceName = ref('')
if(formfullDataSeeion) {
  formfullData.value = formfullDataSeeion
  formfullData.value.isUnitVehicle?formfullData.value.isUnitVehicle = '1' : formfullData.value.isUnitVehicle = '0'
  formfullData.value.isHebeiProvince = formfullDataSeeion.issuingAuthority.indexOf('河北省') > '-1' ? '1' : '0' 
  isHebeiProvinceName.value = formfullData.value.isHebeiProvince == 0 ? '否' : '是'
}
const showRegionPicker = ref(false);
const areaValue = ref([]);
// 单张图片相关
const singleFileList = ref([]);
const singleImageUrl = ref('');
const singleFileListReverseList = ref([]);
const singleImageUrlReverse = ref('');

watch(()=>store.storeNum,(newValue,oldValue)=>{
  store.getFormfullData({...formfullData.value,...store.storeFormfullData})
})
// 处理单张图片上传完成国徽面
const handleSingleReadfrontCard  = async(file) => {
  // 显示上传中状态
  file.status = 'uploading';
  file.message = '上传中...';
  setTimeout(() => {
    singleImageUrl.value = file.content;
    file.status = 'done';
    showToast('上传成功');
  }, 1000);
 const res = await uploadImage(file.file,'id_card_national')
 if(res.code == 200){
   formfullData.value.issuingAuthority = res.data.issuingAuthority
   formfullData.value.validPeriod = res.data.validityPeriod
 }
 showToast(res.msg)
};

// 接口信息返回封装
const uploadImage = async(v,n) => {
  const formData = new FormData();
  formData.append('file', v); 
  formData.append('doc_type', n)
  const res = await recognizeOcr(formData)
  return res
}

// 处理单张图片删除
const handleSingleDeletefrontCard = () => {
  singleFileList.value = []
  singleImageUrl.value = '';
  showToast('图片已删除');
};

// 处理单张图片上传完成人像面
const handleSingleReadreverseCard = async(file) => {
  // 显示上传中状态
  file.status = 'uploading';
  file.message = '上传中...';
  setTimeout(() => {
    singleImageUrlReverse.value = file.content;
    file.status = 'done';
    // showToast('上传成功');
  }, 1000);
  const res = await uploadImage(file.file,'id_card_face')
  if(res.code == 200) {
    formfullData.value.fullName = res.data.name
    formfullData.value.idCard = res.data.idNumber
    formfullData.value.isHebeiProvince = res.data.birthDate.indexOf('河北省') > '-1' ? '1' : '0'
    isHebeiProvinceName.value = formfullData.value.isHebeiProvince == 0 ? '否' : '是'
  }
  showToast(res.msg)
};
// 处理单张图片删除
const handleSingleDeletereverseCard = () => {
  singleFileListReverseList.value = []
  singleImageUrlReverse.value = '';
  showToast('图片已删除');
};

// 社会信用代码证图片地址
const usccImageUrlList = ref([])
const usccImageUrlValue = ref('')

const uploadUsccImageUrl = async(file) => {
  // 显示上传中状态
  file.status = 'uploading';
  file.message = '上传中...';
  setTimeout(() => {
    usccImageUrlValue.value = file.content;
    file.status = 'done';
    // showToast('上传成功');
  }, 1000);
  const formData = new FormData();
  formData.append('file', file.file); 
  formData.append('model', 'social_credit_code')
  const res = await ytbUpload(formData)
  // console.log(res)
};
// 处理单张图片删除
const delUsccImageUrl = () => {
  usccImageUrlList.value = []
  usccImageUrlValue.value = '';
  showToast('图片已删除');
};

// 返回上一页
const handleGoBack = () => {
  // 实际可通过路由返回，如：history.back();
  console.log('返回上一页');
};

// 拍摄身份证
const handleTakePhoto = (type) => {
  // showToast(`即将拍摄身份证${type === 'front'? '国徽面' : '人像面'}`);
  // 实际项目中调用相机或选择图片接口
};

// OCR识别
const handleOcr = (fieldType) => {
  showToast(`即将进行${fieldType}的OCR识别`);
  // 实际项目中调用OCR接口，识别后填充对应字段
};

const columns = [
  { text: '否', value: '0' },
  { text: '是', value: '1' }
];
const onConfirm = ({ selectedValues }) => {
  formfullData.value.isHebeiProvince = selectedValues.join(',')
  isHebeiProvinceName.value = selectedValues.join(',') == 0 ? '否' : '是'
  // showToast(`当前值: ${selectedValues.join(',')}`);
  showRegionPicker.value = false
};
const onChange = ({ selectedValues }) => {
  formfullData.value.isHebeiProvince = selectedValues.join(',')
  isHebeiProvinceName.value = selectedValues.join(',') == 0 ? '否' : '是'
  // showToast(`当前值: ${selectedValues.join(',')}`);
};
</script>

<style lang="less" scoped>
.insurer-info-container {
  width: 100%;
  padding: 16px;
  margin-top: 20px;
  background: #fff;
  border-radius: 10px;
  .container {
    text-align: left;
    font-size: 13px;
    margin-bottom: 10px;
  }
  .company {
    margin-left: 10px;
  }
  .preview-box {
    margin-top: 16px;
    padding: 10px;
    border: 1px solid #eee;
    border-radius: 4px;
    .preview-img {
      max-width: 100%;
      max-height: 300px;
      border-radius: 4px;
      margin-top: 8px;
    }
  }
}
.title {
  font-size: 18px;
  text-align: left;
  font-weight: bold;
  margin-bottom: 16px;
}
.tip {
  color: #f56c6c;
  font-size: 14px;
  display: flex;
  align-items: center;
  margin: 12px 0;
}
.id-card-box {
  display: flex;
  justify-content: space-between;
  margin: 16px 0;
}
.id-card-item {
  width: 48%;
  border: 1px dashed #ddd;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  p {
    font-size: 13px;
  }
}
.field-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}
.field-row.van-field {
  width: 48%;
}
.ocr-btn {
  color: #1989fa;
  cursor: pointer;
}
</style>